$(document)
		.ready(
				function() {
					var contextPath = document.location.pathname;
					var index = contextPath.substr(1).indexOf("/");
					contextPath = contextPath.substr(1, index);
					var basePath = "/" + contextPath;
					
					/*var totalCount = $("#totalCount").val();
					var pSize = $("#pageSize").val();
					var pageIndex = $("#pageIndex").val();
					var pageCount = $("#pageCount").val();
					if(pageCount==null||pageCount=='undefined'){
						pageCount=1;
					}*/
					 var table = document.getElementById('cartTable'); // 购物车表格
					    var selectInputs = document.getElementsByClassName('check'); // 所有勾选框
					    var checkAllInputs = document.getElementsByClassName('check-all'); // 全选框
					    var tr = table.children[1].rows; //行
					    var selectedTotal = document.getElementById('selectedTotal'); //已选商品数目容器
					    var priceTotal = document.getElementById('priceTotal'); //总计
					    var deleteAll = document.getElementById('deleteAll'); // 删除全部按钮
					    var selectedViewList = document.getElementById('selectedViewList'); //浮层已选商品列表容器
					    var selected = document.getElementById('selected'); //已选商品
					    var foot = document.getElementById('foot');
						var checkOneInputs = document.getElementsByClassName('check-one') // 商品选框
						var memberId = $("#memberId").val();
						
						
						
						
					/*$('#pagination2')
							.jqPaginator(
									{
										totalPages : pageCount,
										visiblePages : 10,
										currentPage : 1,
										prev : '<li class="prev"><a href="javascript:void(0);">上一页</a></li>',
										page : '<li class="page"><a href="javascript:void(0);">{{page}}</a></li>',
										next : '<li class="next"><a href="javascript:void(0);">下一页</a></li>',
										onPageChange : function(num, type) {
											var cartTable = $("#cartTable");
											var memberId = $("#memberId").val();
											var queryUrl = "queryByPage.do";
											$.ajax({
														url : queryUrl,
														dataType : 'json',
														data : {
															pageIndex : num,
															pageSize : pSize,
															memberId:memberId
														},
														cache : false,
														success : function(data) {
															$("#cartTable tr:not(:first)").remove();
															var results = data.pageResult.resultList;
															for (i = 0; i < results.length; i++) {
																var car = results[i];
																list.push(car);
																var rowContent = "<tr id='"+i+"'>"
																	+"<td class='checkbox'><input type='hidden' name='details[" + i + "].giftDetailId' value='"+car.giDetailId+"'/><input class='check-one check' type='checkbox' name='giftSelect'/></td>"
																	+"<td class='goods'><input type='hidden' name='details[" + i + "].gdName' value='"+car.giDetailName+"'/><img src='"+basePath+"/HRTWEB/images/car/1.jpg' alt=''/><span>"+car.giDetailName+"</span></td>"
																	+"<td class='price'><input type='hidden' name='details[" + i + "].salePrice' value='"+car.salePrice+"'/>"+car.salePrice+"</td>"
																	+"<td class='count'><span class='reduce'>-</span>"
																	+"<input class='count-input' type='text' name='details[" + i + "].total' value='"+car.total+"'/>"
																	+"<span class='add'>+</span></td>"
																	+"<td class='subtotal'><input type='hidden' name='details[" + i + "].summery' value='"+car.summery+"'/>"+car.summery+"</td>"
																	+"<td class='operation'><span class='delete'  title='"+car.id+"'>删除</span></td>";
																	rowContent = rowContent				
																		+ "</tr>";
																$("#cartTable").append(rowContent);
															}

														},
														error : function(html) {
															return;
														}
													});
											
										}
									});*/
						/**
						 * 在购物车移除礼品
						 */
					$("#cartTable").delegate(
							"span[class='delete']",'click',
							function() {
								if (confirm("是否要删除该记录?") == true) {
									var trId = $(this).attr("title");
									var delUrl = "delItemById.do";
										$.ajax({
													url : delUrl,
													dataType : 'text',
													data : {
														id : trId
													},
													cache : false,

													success : function(data) {
														alert(data);
														refresh();
														return;
													},
													error : function(html) {
														alert("delete Data failly");
														return;
													}
												});
									
								}

							});
					/**
					 * 选择礼品规格
					 */
					$("#cartTable").delegate(
							"input[name='giftSelect']",'click',
							function() {
								var delChk = $('input[name="giftSelect"]:checked');
								if(delChk.length>0){
									$("#settlement").attr("style","width: 100px;height: 50px;background-color: #963;");
									$("#settlement").removeAttr("disabled");
								}
								else{
									$("#settlement").attr("style","width: 100px;height: 50px;background-color: gray;");
									$("#settlement").attr("disabled","disabled");
								}
								getTotal();
							});
					/*
					 * 结算
					 */
					$("#foot").delegate('#settlement', 'click', function() {
						delChk = $('input[name="giftSelect"]:checked');
						if (delChk.length > 0) {
							if (confirm("确定购买吗?")) {
								var ids = "";
								var idArr = new Array();
								for (var i = 0; i < delChk.length; i++) {
									idArr.push(delChk.get(i).value);

								}
								ids = idArr.toString();
								window.location.assign(basePath+"/HRTWEB/shoppingCar.do?ids="+ids+"&memberId="+memberId);
								
							} else {
								return;
							}
						} else {
							alert("请选择您想要购买的礼品！");
							return;
						}
					});
					

					
					if (!document.getElementsByClassName) {
				        document.getElementsByClassName = function (cls) {
				            var ret = [];
				            var els = document.getElementsByTagName('*');
				            for (var i = 0, len = els.length; i < len; i++) {

				                if (els[i].className.indexOf(cls + ' ') >=0 || els[i].className.indexOf(' ' + cls + ' ') >=0 || els[i].className.indexOf(' ' + cls) >=0) {
				                    ret.push(els[i]);
				                }
				            }
				            return ret;
				        }
				    }

				   

				    // 更新总数和总价格，已选浮层
				    function getTotal() {
				    	
						var seleted = 0;
						var totalPrice = 0;
						var HTMLstr = '';
						for (var i = 1;i<tr.length+1; i++) {
							var tableRow=document.getElementsByTagName("tr")[i];
							if (tableRow.getElementsByTagName('input')[0].checked) {
								var price = parseFloat(tableRow.getElementsByTagName('td')[4].innerHTML);
								
								var total = tableRow.getElementsByTagName('td')[3].getElementsByTagName('input')[0].value;
								seleted += parseInt(total);
								totalPrice += price;
								HTMLstr += '<div><img src="' + tableRow.getElementsByTagName('img')[0].src + '"><span class="del" index="' + i + '">取消选择</span></div>'
							}
							else {
								tableRow.className = '';
							}
						}	
						selectedTotal.innerHTML = seleted;
						priceTotal.innerHTML = totalPrice;
						selectedViewList.innerHTML = HTMLstr;
					
						if (seleted == 0) {
							foot.className = 'foot';
						}
					}
				    // 计算单行价格
				    function getSubtotal(tr) {
				        var cells = tr.cells;
				        var price = parseInt(cells[2].innerHTML); //单价
				        var subtotal = cells[4]; //小计td
				        var countInput = tr.getElementsByTagName("td")[3].getElementsByTagName("input")[0];
				        cells[3].getElementsByTagName('input')[0].value = countInput.value;
				        var span = tr.getElementsByTagName('span')[1]; //-号
				        //写入HTML
				        subtotal.innerHTML = (parseInt(countInput.value) * parseFloat(price)).toFixed(2);
				        //如果数目只有一个，把-号去掉
				        if (countInput.value == 1) {
				            span.innerHTML = '';
				        }else{
				            span.innerHTML = '-';
				        }
				        
				        
				    }
				  
				    // 点击选择框
				    for(var i = 0; i < selectInputs.length; i++ ){
				        selectInputs[i].onclick = function () {
				           if (this.className.indexOf('check-all') >= 0) { //如果是全选，则把所有的选择框选中
				        	   for (var j = 0; j < selectInputs.length; j++) {
				                    selectInputs[j].checked = this.checked;
				                    var delChk = $('input[name="giftSelect"]:checked');
									if(delChk.length>0){
										$("#settlement").attr("style","width: 100px;height: 50px;background-color: #963;");
										$("#settlement").removeAttr("disabled");
									}
									else{
										$("#settlement").attr("style","width: 100px;height: 50px;background-color: gray;");
										$("#settlement").attr("disabled","disabled");
									}
									
				                }
				            }
				            if (!this.checked) { //只要有一个未勾选，则取消全选框的选中状态
				                for (var i = 0; i < checkAllInputs.length; i++) {
				                    checkAllInputs[i].checked = false;
				                }
				            }
							
							 var num = 0;//选中商品开始的数量；
							 for(var n = 0; n < checkOneInputs.length;n++) {
								if(checkOneInputs[n].checked== true) {//选中商品的数量；
									num++;
							    }
							 }
							 
							 //如果所有的商品都选择了，则把全选框设置选中状态
							if((selectInputs.length-2)==num){
								for (var i = 0; i < checkAllInputs.length; i++) {
				                    checkAllInputs[i].checked = true;
				                }
							}
							
				            getTotal();//选完更新总计
				        }
				    }
					

				    // 显示已选商品弹层
				    selected.onclick = function () {
				        if (selectedTotal.innerHTML != 0) {
				            foot.className = (foot.className == 'foot' ? 'foot show' : 'foot');
				        }
				    }

				    //已选商品弹层中的取消选择按钮
				    selectedViewList.onclick = function (e) {
				        var e = e || window.event;
				        var el = e.srcElement;
				        if (el.className=='del') {
				            var input =  tr[el.getAttribute('index')].getElementsByTagName('input')[0]
				            input.checked = false;
				            input.onclick();
				        }
				    }
				   
				    //为每行元素添加事件
				    for (var i = 1; i < tr.length+1; i++) {
				    	var tableRow=document.getElementsByTagName("tr")[i];
				        //将点击事件绑定到tr元素
				    	tableRow.onclick = function (e) {
				            var e = e || window.event;
				            var el = e.target || e.srcElement; //通过事件对象的target属性获取触发元素
				            var cls = el.className; //触发元素的class
				            var countInout = this.getElementsByTagName("td")[3].getElementsByTagName("input")[0]; // 数目input
				           
				            var value = parseInt(countInout.value); //数目
				            //通过判断触发元素的class确定用户点击了哪个元素
				            switch (cls) {
				                case 'add': //点击了加号
				                	var carId = $(this).attr("id");
				                	var objId = $(this).attr("objId");
				                	countInout.value = value + 1;
				                	var total = countInout.value;
				                	changeShoppingCar(carId,total,objId);
				                    getSubtotal(this);
				                    getTotal();
				                    break;
				                case 'reduce': //点击了减号
				                    if (value > 1) {
				                    	var carId = $(this).attr("id");
				                    	var objId = $(this).attr("objId");
				                        countInout.value = value - 1;
				                        getSubtotal(this);
				                        var total = countInout.value;
					                	changeShoppingCar(carId,total,objId);
					                	 getTotal();
				                    }
				                    break;
				                
				            }
				           
				        }
				        // 给数目输入框绑定keyup事件
				        tableRow.getElementsByTagName('input')[1].onkeyup = function () {
				            var val = parseInt(this.value);
				            var carId = $(this).parent().parent().attr("id");
		                	var objId = $(this).parent().parent().attr("objId");
				            if (isNaN(val) || val <= 0) {
				                val = 1;
				            }
				            if (this.value != val) {
				                this.value = val;
				            }
				            getSubtotal(this.parentNode.parentNode); //更新小计
				            changeShoppingCar(carId,val,objId);
				            getTotal(); //更新总数
				        }
				    }
				   /* // 点击全部删除
				    deleteAll.onclick = function () {
				        if (selectedTotal.innerHTML != 0) {
				            var con = confirm('确定删除所选商品吗？'); //弹出确认框
				            if (con) {
				                for (var i = 0; i < tr.length; i++) {
				                    // 如果被选中，就删除相应的行
				                    if (tr[i].getElementsByTagName('input')[0].checked) {
				                        tr[i].parentNode.removeChild(tr[0]); // 删除相应节点
				                        i--; //回退下标位置
				                    }
				                }
				            }
				        } else {
				            alert('请选择商品！');
				        }
				        getTotal(); //更新总数
				    }*/
				    //多删除
				    $("#foot").delegate('#deleteAll', 'click', function() {
						delChk = $('input[name="giftSelect"]:checked');

						if (delChk.length > 0) {
							if (confirm("确定要删除吗?")) {
								var ids = "";
								var delUrl = basePath+"/HRTWEB/deleteAll.do"
								var idArr = new Array();
								for (var i = 0; i < delChk.length; i++) {
									idArr.push(delChk.get(i).value);

								}
								$.ajax({
									url : delUrl,
									type : "POST",
									data : {
										ids : idArr.toString()
									},
									cache : false,

									success : function(html) {
										alert("Delete successfully");
										refresh();
									},
									error : function(html) {
										alert("Delete failly");
										refresh();
									}
								});
								
							} else {
								return;
							}
						} else {
							alert("请选择您想要删除的礼品！");
							return;
						}
					});
				    
				    // 默认全选
				    //checkAllInputs[0].checked = true;
				    //checkAllInputs[0].onclick();
					
				});

function refresh() {
	window.location.reload();
}


function getData(memberId){
	var queryUrl = "listCar.do";
	$.ajax({
		url : queryUrl,
		dataType : 'json',
		data : {
			memberId:memberId
		},
		success : function(data) {
			alert("success");
		},
		error : function(html) {
			alert("failure!!");
			return;
		}
	});
	
}

function changeShoppingCar(carId,total,objId){
	var queryUrl = "changeShoppingCar.do";
	$.ajax({
		url : queryUrl,
		dataType : 'json',
		data : {
			carId:carId,
			total:total
		},
		success : function(data) {
			
			alert("操作成功！");
		},
		error : function(html) {
			alert("failure!!");
			return;
		}
	});
}


